"""
$Id: simul.py 2 2007-03-04 19:08:44Z sidnei.da.silva $
"""

import time
import random
import logging
import threading
from voting import constants

class Simulator(threading.Thread):

    def __init__(self, zone_id, sections, electors, sleep=1):
        threading.Thread.__init__(self)
        self.setDaemon(False)
        self.logger = logging.getLogger('voting.simul.zone-%s' % zone_id)
        self.shutdown = False
        self.sections = sections
        self.electors = list(electors)
        self.sleep = sleep

    def run(self):
        try:
            try:
                for elector in self.electors:
                    if self.shutdown:
                        return
                    vote = random.choice(constants.VALID_CHOICES)
                    section_id, section = random.choice(self.sections)
                    self.logger.debug('Choosen section %s for '
                                      'voting with elector %s',
                                      section_id, elector)
                    section.vote(elector, vote)
                    if self.sleep:
                        time.sleep(self.sleep)
            except:
                self.logger.exception('Exception...')
        finally:
            self.logger.info('Finished')

    def stop(self):
        self.shutdown = True
